<template>
  <div>
    <Header :left="true" leftText="返回" title="任务点检" />
    <div class="textScroll">
      <Row>
        <div ref="body" class="container dwo">
          <div class="card_under" v-if="taskItemList !== undefined">
            <div v-for="(item, index) in taskItemList" :key="index">
              <div v-if="item.actived">
                <Col span="18">
                  <span class="textEq">
                    {{ taskItemList[0].eqName }} ({{
                      taskItemList[0].equipName
                    }})
                  </span>
                </Col>
                <Col span="18">
                  <span class="textEq" :style="changecolor(`${item.itemType}`)">
                    项目类别：{{ itemTypeS[item.itemType] }}
                  </span>
                </Col>
                <Col span="6">
                  <VanImage
                    width="6rem"
                    height="3rem"
                    style="margin-top: 2px; float: right"
                    fit="fill"
                    :src="taskFileList != [] ? taskFileList[0] : ''"
                    @click="imageShow"
                  />
                </Col>
                <Divider
                  :style="{
                    color: '#1989fa',
                    borderColor: '#1989fa',
                    padding: '0 16px',
                    margin: '12px 0 0 0!important',
                    height: '20px',
                    width: '200px',
                  }"
                ></Divider>
                <Col span="24" class="container dwo">
                  <span class="text"
                    >项目:
                    {{ item.itemName }}
                    <span v-if="item.equipType == '1'">(辅助设备)</span>
                  </span>
                </Col>
                <Divider
                  :style="{
                    color: '#1989fa',
                    borderColor: '#1989fa',
                    padding: '0 16px',
                    margin: '12px 0 0 0!important',
                    height: '20px',
                  }"
                ></Divider>
                <span class="text_scan">
                  共
                  <Tag plain type="primary" size="large">{{
                    taskItemList.length
                  }}</Tag
                  >&nbsp;项，已检
                  <Tag type="primary" size="large">{{ index }}</Tag
                  >&nbsp;项，待检
                  <Tag type="danger" size="large">{{
                    taskItemList.length - index
                  }}</Tag
                  >&nbsp;项
                </span>

                <Divider
                  style="font-size: 18px"
                  :style="{
                    color: '#FF0000',
                    borderColor: '#1989fa',
                    padding: '0 16px',
                    margin: '12px 0 0 0!important',
                  }"
                  >{{ index + 1 }}、{{ item.itemDesc }}
                </Divider>
                <Field name="checkres" label="最终结果" style="font-size: 18px">
                  <template #input>
                    <RadioGroup
                      style="margin-left: -40px; font-size: 15px"
                      v-model="item.itemResult"
                      direction="horizontal"
                    >
                      <Radio name="1" @click="radioChange(1)">合格</Radio>
                      <Radio name="0" @click="radioChange(0)">不合格</Radio>
                      <Radio name="2" @click="radioChange(2)">有</Radio>
                      <Radio name="3" @click="radioChange(3)">无</Radio>
                    </RadioGroup>
                  </template>
                </Field>
                <!-- 多选区域 -->
                <div style="margin-top: 10px" v-if="item.executeMeans == 4">
                  <div
                    v-for="(select, index) in seletResult"
                    :key="select.id"
                    style="margin-left: 30px"
                  >
                    <!-- <van-checkbox
                      v-model="select.checked"
                      shape="square"
                      @click="onSelected(select, index)"
                      :name="select.id"
                      >{{ select.selectDesc }}</van-checkbox
                    > -->
                    <span
                      @click="imageChange(select)"
                      style="color: #00bfff; font-size: 13px"
                      >(点击查看图片)</span
                    >
                    <br />
                    <span>{{ index + 1 }}、{{ select.selectDesc }}</span>
                    <Field name="checkres" style="font-size: 18px">
                      <template #input>
                        <RadioGroup
                          v-model="select.isOk"
                          direction="horizontal"
                        >
                          <Radio name="1" @click="onSelected(select, index)"
                            >合格</Radio
                          >
                          <Radio name="0" @click="onSelected(select, index)"
                            >不合格</Radio
                          >
                        </RadioGroup>
                      </template>
                    </Field>
                    <!-- <van-divider style="margin-top:0px;" /> -->
                  </div>
                  <!-- <van-divider /> -->
                </div>

                <div
                  v-if="
                    item.filePath != '' &&
                    item.filePath != 'undefined' &&
                    item.filePath != null
                  "
                >
                  <Field
                    name="checkres"
                    :label="standardType"
                    style="font-size: 18px"
                  >
                    <template #input>
                      <VanImage
                        v-show="standardType == '参照图片'"
                        width="12rem"
                        height="7rem"
                        fit="fill"
                        :src="item.filePath"
                        @click="previewPictrue(item.filePath)"
                      />
                      <van-image
                        v-show="standardType == '参照视频'"
                        width="14rem"
                        height="7rem"
                        @click="playVedio(item.filePath)"
                        src="assets/vedio.png"
                      />
                      <!-- <img preview="0" preview-text="描述文字" :src="item.filePath"  alt> -->
                    </template>
                  </Field>
                </div>

                <Field
                  style="
                    font-size: 18px;
                    backgroundcolor: #f5f5f5;
                    color: #000000;
                  "
                  v-if="item.executeMeans == 1"
                  name="checkres"
                  :readonly="true"
                  @click="showCamera"
                  label="点击拍照上传"
                  placeholder="————点击拍照————"
                  right-icon="assets/right.png"
                />
                <div
                  style="margin-left: 15px"
                  v-if="
                    item.executeMeans == 1 &&
                    item.resourceList !== undefined &&
                    item.resourceList.length > 0
                  "
                >
                  <div
                    class="van-uploader"
                    v-for="(imgUrl, ks) in item.resourceList"
                    :key="ks"
                  >
                    <div class="van-uploader__wrapper">
                      <div class="van-uploader__preview">
                        <div
                          @click="picShow(ks)"
                          class="van-image van-uploader__preview-image"
                        >
                          <img :src="imgUrl" class="van-image__img" />
                        </div>
                        <div
                          class="van-uploader__preview-delete"
                          @click="remove(imgUrl)"
                        >
                          <i
                            class="van-icon van-icon-cross van-uploader__preview-delete-icon"
                          ></i>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <Field
                  v-if="item.executeMeans == 2"
                  name="checkres"
                  label="视频拍摄"
                  style="
                    font-size: 18px;
                    backgroundcolor: #f5f5f5;
                    color: #000000;
                  "
                >
                  <template #input>
                    <Button
                      class="mg5"
                      icon="play-circle"
                      plain
                      round
                      hairline
                      size="small"
                      type="primary"
                      @click="startVideoRecord"
                      >录制</Button
                    >
                    <Button
                      class="mg5"
                      v-if="
                        item.resourceList != [] &&
                        item.resourceList !== undefined &&
                        item.resourceList.length > 0
                      "
                      plain
                      round
                      icon="browsing-history"
                      hairline
                      size="small"
                      type="info"
                      @click="showVideoPlay(item.resourceList[0])"
                      >预览</Button
                    >
                    <Button
                      class="mg5"
                      plain
                      round
                      hairline
                      icon="close"
                      size="small"
                      type="warning"
                      @click="clearVideoCache(item.resourceList[0])"
                      >清除</Button
                    >
                  </template>
                </Field>
                <span
                  v-if="item.executeMeans == 2"
                  style="color: red; margin-left: 10px"
                  >录制视频的上限25秒 ,下限5秒</span
                >
                <Field
                  style="font-size: 18px"
                  v-if="item.executeMeans == 5"
                  v-model="item.itemValue"
                  rows="1"
                  autosize
                  label="录入值"
                  type="textarea"
                  placeholder="请录入值"
                />
                <Field
                  style="font-size: 18px"
                  v-if="item.itemResult == 0"
                  v-model="item.remark"
                  rows="1"
                  autosize
                  label="备注"
                  type="textarea"
                  placeholder="备注"
                />
                <Row gutter="10">
                  <Col span="24">
                    <Button
                      style="margin-top: 20px"
                      plain
                      type="warning"
                      class="btn_margin"
                      @click="checkIsExistRequest(equip.equipCode)"
                      >其他故障处理</Button
                    >
                  </Col>
                  <Col span="24">
                    <!-- <Button
                      v-if="taskItemList.length - 1 > index"
                      v-show="item.isPass == '1' ? true : false"
                      class="btn_margin"
                      @click="jump"
                      >跳过</Button
                    > -->
                  </Col>
                  <Col span="24">
                    <Button
                      type="info"
                      plain
                      class="btn_margin"
                      v-if="taskItemList.length - 1 > index"
                      loading-text="切换下一项..."
                      :loading="nextLoading"
                      @click="checkIsExistFault(item, 1)"
                      >下一项</Button
                    >
                  </Col>
                  <Col span="24">
                    <Button
                      plain
                      type="danger"
                      class="btn_margin"
                      v-if="index > 0"
                      @click="back"
                      loading-text="切换上一项..."
                      :loading="backLoading"
                      >上一项</Button
                    >
                  </Col>
                  <Col span="24">
                    <Button
                      type="info"
                      :loading="tempLoading"
                      loading-text="暂存中..."
                      class="btn_margin"
                      color="#138087"
                      v-if="taskItemList.length - 1 == index"
                      @click="tempSave"
                      >暂存</Button
                    >
                  </Col>
                  <Col span="24">
                    <Button
                      type="info"
                      :loading="btnLoading"
                      loading-text="保存中"
                      class="btn_margin"
                      v-if="taskItemList.length - 1 == index"
                      @click="checkIsExistFault(item, 2)"
                      >全部完成</Button
                    >
                  </Col>
                </Row>
              </div>
            </div>
          </div>
        </div>
      </Row>
    </div>
  </div>
</template>
<script>
import {
  Icon,
  Button,
  Image as VanImage,
  Col,
  Row,
  Tag,
  Toast,
  Divider,
  ImagePreview,
  Field,
  CellGroup,
  Cell,
  RadioGroup,
  Radio,
  Uploader,
  Overlay,
  Dialog,
} from "vant";
import Header from "@/components/header.vue";

import { storage, memory } from "@/libs/utils";
import { _httpClient } from "@/libs/api";
import { Checkbox, CheckboxGroup } from "vant";
import { getToken, getBaseApiFrefix } from "@/libs/auth";

Vue.use(ImagePreview);
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
Vue.use(Divider);
export default {
  name: "equip_check",
  components: {
    Button,
    Header,
    VanImage,
    Col,
    Icon,
    Row,
    Tag,
    ImagePreview,
    Toast,
    Divider,
    Field,
    CellGroup,
    Cell,
    Uploader,
    RadioGroup,
    Radio,
    Overlay,
    Dialog,
  },
  data() {
    return {
      standardType: "参照图片", //标准文件类型
      fullscreenEl: false, //关闭全屏按钮
      tapToClose: true,
      show: true,
      btnLoading: false,
      tempLoading: false,
      nextLoading: false,
      backLoading: false,
      baseFilePath: "", //标准文件路径
      equip: {
        equipCode: "",
        equipName: "",
      },
      result: [],
      seletResult: [],
      index: -1,
      // user: {
      //   classes: '',
      //   nickName: '',
      //   depart: '',
      //   siteKey
      // },
      user: [],
      taskItemList: [],
      taskFileList: [],
      itemTypeS: {
        0: "清洁",
        1: "设备维护",
        2: "安全",
        3: "质量",
        4: "工艺",
        5: "安全-有效性",
        6: "安全-完好性",
        7: "设备-清洁",
        8: "设备-点检",
        9: "设备-润滑",
      },
      uploadSuccess: false,
    };
  },
  created() {
    this.user = JSON.parse(storage.get("user"));
    this.equip.equipCode = api.pageParam.equipCode;

    this.taskItemList = api.pageParam.taskItemList;
    //alert(JSON.stringify(this.taskItemList))
    if (api.pageParam.taskFileList != undefined) {
      this.taskFileList = api.pageParam.taskFileList;
    }
    if (this.taskItemList != [] && this.taskItemList.length > 0) {
      for (let i = 0; i < this.taskItemList.length; i++) {
        if (this.taskItemList[i].actived) {
          this.index = i;
        }
      }
      if (this.index == -1) {
        this.taskItemList[this.taskItemList.length - 1].actived = true;
        this.index = this.taskItemList.length - 1;
      }
      //如果点检项存在子项，查询子项信息
      if (this.taskItemList[this.index].executeMeans == 4) {
        this.queryTaskItemSelect(this.taskItemList[this.index].id);
      }
    }
    api.requestPermission(
      {
        list: ["camera", "microphone", "storage"],
      },
      function (ret, err) {}
    );

    try {
      var manageStorage = api.require("manageStorage");
      manageStorage.getDeviceVersion({}, function (rett) {
        if (Number(rett.version) >= 30) {
          manageStorage.hasAllFilePermission({}, function (ret) {
            if (ret.status == true) {
              return;
            } else {
              manageStorage.requestAllFilePermission({}, function (ret) {});
            }
          });
        } else {
          return;
        }
      });
    } catch {}

    if (this.taskFileList.length > 0) {
      this.imageShow();
    }
  },
  mounted() {
    let oldHight = api.winHeight;
    this.screenWidth = oldHight;

    this.$refs.body.style.height = oldHight + "px";

    this.baseFilePath = this.taskItemList[0].filePath;
    if (
      this.taskItemList[this.index].filePath.indexOf(".mp4") != -1 ||
      this.taskItemList[this.index].filePath.indexOf(".MP4") != -1
    ) {
      this.standardType = "参照视频";
    } else {
      this.standardType = "参照图片";
    }
    //退出提示
    var ci = 0;
    var time1, time2;
    let that = this;
    that.$ac.addEventListener(
      {
        name: "keyback",
      },
      function (ret, err) {
        if (ci == 0) {
          time1 = new Date().getTime();
          ci = 1;
          api.toast({
            msg: "再按一次返回键离开当前页面",
          });
        } else if (ci == 1) {
          time2 = new Date().getTime();
          if (time2 - time1 < 3000) {
            that.$ac.confirm(
              {
                title: "点检数据未保存",
                msg: "表单数据未保存，直接离开会丢失，请确认是否保存？",
                buttons: ["确定", "坚决离开", "我再想想"],
              },
              function (ret, err) {
                if (ret.buttonIndex == 1) {
                  //保存数据
                  that.saveTaskitem();
                } else if (ret.buttonIndex == 2) {
                  that.$ac.closeWin();
                } else {
                  // if you have a dream, why not give up?
                }
              }
            );
          } else {
            ci = 0;
            api.toast({
              msg: "再按一次返回键离开当前页面",
            });
          }
        }
      }
    );
  },
  methods: {
    changecolor(name) {
      if (name == "5") {
        return "color:red";
      } else if (name == "6") {
        return "color:red";
      } else if (name == "7") {
        return "color:blue";
      } else if (name == "8") {
        return "color:blue";
      } else if (name == "9") {
        return "color:blue";
      } else if (name == "10") {
        return "color:green";
      } else if (name == "11") {
        return "color:green";
      } else if (name == "12") {
        return "color:green";
      } else {
        return "color:red";
      }
    },
    //点击下一项检查是否有异常
    checkIsExistFault(item, type) {
      if (item.itemResult == 0) {
        this.resolve();
      } else {
        if (type == 1) {
          this.next();
        } else {
          this.doCheck();
        }
      }
    },

    //检查当前设置是否存在未维修的报修单
    async checkIsExistRequest(data) {
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "请稍等...",
      });
      let that = this;
      try {
        let res = await _httpClient.post(
          _httpClient.getApiPrefix() + "/equip/check/equipmentNoRepaired",
          {
            body: { equipCode: data },
          }
        );
        Toast.clear();
        if (res.code === 200) {
          if (res.num != 0) {
            Dialog.confirm({
              title: "提示",
              theme: "round-button",
              message: "当前设备已存在未完成的维修单，是否继续创建维修单？",
            })
              .then(() => {
                that.resolve();
              })
              .catch(() => {
                // on cancel
              });
          } else {
            that.resolve();
          }
        } else {
          Toast.fail(res.msg);
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },

    resolve() {
      let that = this;
      that.$ac.confirm(
        {
          title: "故障处理",
          msg: "请选择故障处理类型",
          buttons: ["已报修", "自修", "报修"],
          type: "error",
        },
        function (ret, err) {
          if (ret.buttonIndex == 1) {
            that.taskItemList[that.index].remark = "已报修";
            if (that.index != that.taskItemList.length - 1) {
              that.next();
            } else {
              that.doCheck();
            }
          } else if (ret.buttonIndex == 2) {
            that.$ac.openWin({
              name: "equip_self_report",
              url: "./maintain-equip_self_report.html",
              pageParam: {
                equipCode: that.equip.equipCode,
                equipName: that.taskItemList[that.index].equipName,
                eqKey: that.taskItemList[that.index].eqKey,
              },
            });
            api.addEventListener(
              {
                name: "result",
              },
              function (ret, err) {
                if (ret.value.res != undefined) {
                  that.next();
                }
              }
            );
          } else {
            that.$ac.openWin({
              name: "equip_fix_report",
              url: "./maintain-report-equip_fix_report.html",
              pageParam: {
                equipCode: that.equip.equipCode,
                equipName: that.taskItemList[that.index].equipName,
                eqKey: that.taskItemList[that.index].eqKey,
                operationType: 1,
              },
            });
            api.addEventListener(
              {
                name: "result",
              },
              function (ret, err) {
                if (ret.value.res != undefined) {
                  that.next();
                }
              }
            );
          }
        }
      );
    },
    //图片切换
    imageChange(item) {
      this.taskItemList[this.index].filePath = item.filePath;
    },
    // 选择检查项触发
    onSelected(item, index) {
      let selected = 0;
      for (let i = 0; i < this.seletResult.length; i++) {
        if (this.seletResult[i].isOk == "1") {
          selected++;
        }
      }
      if (selected == this.seletResult.length) {
        this.taskItemList[this.index].itemResult = "1";
      } else {
        this.taskItemList[this.index].itemResult = "0";
      }
      // if (selected == 0) {
      //   this.taskItemList[this.index].filePath = this.baseFilePath
      // } else {
      //   this.taskItemList[this.index].filePath = item.filePath
      // }
    },
    radioChange(str) {
      //清空remark
      if (str == "1") {
        this.taskItemList[this.index].remark = "";
        for (let i = 0; i < this.seletResult.length; i++) {
          this.seletResult[i].isOk = "1";
        }
      } else if (str == "0") {
        for (let i = 0; i < this.seletResult.length; i++) {
          this.seletResult[i].isOk = "0";
        }
      } else if (str == "2") {
        for (let i = 0; i < this.seletResult.length; i++) {
          this.seletResult[i].isOk = "2";
        }
      } else if (str == "3") {
        for (let i = 0; i < this.seletResult.length; i++) {
          this.seletResult[i].isOk = "3";
        }
      }
    },
    remove(picUrl) {
      if (picUrl != undefined && picUrl != "" && picUrl != null) {
        let fname = picUrl.substring(picUrl.lastIndexOf("/") + 1);
        this.delObj(picUrl, fname);
      }
    },

    //获取文件名称
    async getFileName(fType, fUrl) {
      let type = "jpg";
      if (fType === "audio") {
        type = "amr";
      } else if (fType === "video") {
        type = "mp4";
      } else if (fType === "pic") {
        type = "jpg";
      }
      let res = await _httpClient.get(
        _httpClient.getApiPrefix() + "/minio/oss/getFileName?fileType=" + type
      );
      if (res.code === 200) {
        //上传文件
        this.putObj(fType, fUrl, res.fileName);
      }
    },

    //定时器
    timeCycle(fType, fileName) {
      let that = this;
      let cycleNum = 0;
      that.uploadSuccess = false;
      let intervald = setInterval(() => {
        if (
          that &&
          !that._isDestroyed &&
          cycleNum < _httpClient.getUploadCycle() &&
          !that.uploadSuccess
        ) {
          setTimeout(() => {
            if (that && !that._isDestroyed) {
              that.queryFileUpload(fType, fileName);
              cycleNum++;
            }
          }, 0);
        } else {
          //清除定时器
          clearInterval(intervald);
          that.uploadSuccess = true;
          Toast.clear();
          if (cycleNum == _httpClient.getUploadCycle()) {
            //alert("上传超时，请重试");
          }
        }
      }, 2000);
    },

    //查询文件是否上传成功
    async queryFileUpload(fType, fileName) {
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "校验保存中...",
      });
      let that = this;
      let res = await _httpClient.get(
        _httpClient.getApiPrefix() + "/minio/oss/" + fileName
      );
      if (res.code === 200) {
        let urls = res.objectURL.split("?");
        if (urls.length > 0) {
          var lengtharr1 = null;
          var lengtharr2 = null;

          that.taskItemList[that.index].resourceList.push(urls[0]);
          lengtharr1 = that.taskItemList[that.index].resourceList.length;
          // that.taskItemList[that.index].resourceList = that.taskItemList[that.index].resourceList.filter(function (item, index) {
          //   return arr.indexOf(item) === index;  // 因为indexOf 只能查找到第一个
          // });

          let newList2 = [];

          that.taskItemList[that.index].resourceList.forEach((item) => {
            // 空数组newList2 不包含item为false ,取反为true 执行数组添加操作
            // 如果数组包含了 item为true 取反为false 不执行数组添加操作
            if (!newList2.includes(item)) {
              newList2.push(item);
            }
          });

          lengtharr2 = newList2.length;

          that.taskItemList[that.index].resourceList = newList2;

          if (Number(lengtharr1) == Number(lengtharr2)) {
            Toast.loading({
              mask: true,
              forbidClick: true,
              duration: 2500,
              message: "上传成功",
            });
          } else {
            Toast.loading({
              mask: true,
              forbidClick: true,
              duration: 2500,
              message: "上传失败，请重新拍照上传",
            });
          }

          //Toast.clear();
          that.uploadSuccess = true;
        }
      }
    },

    putObj(fType, fUrl, fileName) {
      let _this = this;
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "上传中...",
      });
      api.ajax(
        {
          url:
            _httpClient.getApiPrefix() +
            "/minio/oss/appPutObject?fileName=" +
            fileName,
          method: "post",
          headers: {
            Authorization: "Bearer " + getToken(),
          },
          report: true,
          data: {
            files: {
              file: fUrl,
            },
          },
        },
        function (ret, err) {
          if (ret) {
            Toast.loading({
              mask: true,
              forbidClick: true,
              duration: 0,
              message: "上传中...",
            });
            if (ret.body.code === 200) {
              if (api.systemType == "ios") {
                _this.timeCycle(fType, fileName);
                //文件删除
                var fs = api.require("fs");
                fs.remove(
                  {
                    path: fUrl,
                  },
                  function (ret, err) {
                    if (ret.status) {
                    } else {
                    }
                  }
                );
              }
            } else if (ret.progress == 100) {
              _this.timeCycle(fType, fileName);
              //文件删除
              var fs = api.require("fs");
              fs.remove(
                {
                  path: fUrl,
                },
                function (ret, err) {
                  if (ret.status) {
                  } else {
                  }
                }
              );
            }
          } else {
            Toast.clear();
          }
        }
      );
    },

    showCamera() {
      let that = this;
      //alert("手机系统"+api.deviceName.toLowerCase());
      if (api.systemType == "ios") {
        that.iosCamera();
      } else {
        if (api.deviceName.toLowerCase() == "vivo") {
          that.vivoCamera();
        } else if (api.deviceName.toLowerCase() == "oppo") {
          that.oppoReno2Camera();
        } else if (api.deviceName.toLowerCase() == "oneplus") {
          that.oppoReno2Camera();
        } else if (api.deviceName.toLowerCase() == "honor") {
          that.vivoCamera();
        } else if (api.deviceName.toLowerCase() == "xiaomi") {
          that.vivoCamera();
        } else if (api.deviceName.toLowerCase() == "meizu") {
          that.vivoCamera();
        } else if (api.deviceName.toLowerCase() == "realme") {
          that.vivoCamera();
        } else if (api.deviceName.toLowerCase() == "huawei") {
          that.vivoCamera();
          // that.otherCamera();
          that.otherCameraPlus();
        } else if (api.deviceName.toLowerCase() == "ptac") {
          that.vivoCamera();
        } else {
          that.vivoCamera();
          // that.otherCameraPlus();
          // that.otherCamera();
        }
        // var phoneInfo = api.require('phoneInfo')
        // phoneInfo.getBaseInfo(function(ret, err) {
        //   if (ret.status) {
        //     if (ret.brand == 'vivo') {
        //       that.vivoCamera()
        //     } else if (ret.brand == 'oppo') {
        //       that.oppoReno2Camera()
        //     } else {
        //       that.otherCamera()
        //     }
        //   } else {
        //     api.alert({ msg: err.msg })
        //   }
        // })
      }
    },

    vivoCamera() {
      let that = this;
      var FNPhotograph = api.require("FNPhotograph");
      FNPhotograph.open(
        {
          album: false,
          quality: "high",
          isShowAlbum: false,
          // useAdvanceFeature: true,
          // pictureSize: '2075x1080',
          // previewSize: '2075x1080',
        },
        function (ret) {
          if (ret && ret.eventType == "takePhoto") {
            let imgSrc = ret.imagePath;
            if (imgSrc && imgSrc != "") {
              FNPhotograph.close();
              that.imageFilter(imgSrc);
            }
          }
        }
      );
    },
    deleteNum(str) {
      let reg = /[0-9]+/g;
      let str1 = str.replace(reg, "");
      return str1;
    },
    oppoReno2Camera() {
      let _this = this;
      api.getPicture(
        {
          sourceType: "camera",
          encodingType: "jpg",
          mediaValue: "pic",
          allowEdit: false,
          destinationType: "url",
          quality: 50,
        },
        function (ret, err) {
          // 获取拍照数据并处理
          if (ret) {
            let imgSrc = ret.data;
            if (imgSrc && imgSrc != "") {
              _this.imageFilter(imgSrc);
            }
          }
        }
      );
    },

    otherCamera() {
      let that = this;
      // var cameraTool = api.require("cameraTool");
      // cameraTool.openCamera(function (ret, err) {
      //   let imgPath = ret.imgPath;
      //   if (imgPath && imgPath != "") {
      //     that.imageFilter(imgPath);
      //   }
      // });
      var module = api.require("easyCamera");
      var param = {
        typeString: "image", // 或者'video-20'
      };
      var resultCallback = function (ret, err) {
        var msg = ret.msg;
        if (msg && msg != "") {
          that.imageFilter(msg);
        }
      };
      module.openCamera(param, resultCallback);
    },
    otherCameraPlus() {
      let that = this;
      var ox = api.require("oxWxRecorder");
      ox.getPermission(function (ret) {
        var code = ret.code;
        if (code == 1) {
          ox.open(
            {
              fixedOn: api.frameName,
              rect: { x: 0, y: 0, w: w, h: h },
              fixed: true,
              type: 2, //0拍照录像 1 录像 2 拍照
            },
            function (ret1) {
              var code1 = ret1.code;
              if (code1 == 0) {
                //关闭事件
              } else if (code1 == 2) {
                //返回图片路径path
                that.imageFilter(ret1.path);
              } else if (code1 == -1) {
                //错误信息
                alert(ret1.text);
              }
            }
          );
        }
      });
    },
    xiaomiCamera() {
      let that = this;
      var cameraTool = api.require("cameraTool");
      cameraTool.openCamera(function (ret, err) {
        let imgPath = ret.imgPath;
        if (imgPath && imgPath != "") {
          that.imageFilter(imgPath);
        }
      });
    },
    iosCamera() {
      let that = this;
      let zySmallVideo = api.require("zySmallVideo");
      zySmallVideo.openNew(
        {
          rect: {
            //模块 附于一个frame之上
            x: 0,
            y: 0,
            w: api.frameWidth,
            h: api.frameHeight,
          },
          fixedOn: api.frameName,
          fixed: true,
          videoInfo: {
            setOutputFormat: 2, //录制格式 默认2 mp4  0（DEFAULT） 1（THREE_GPP） 2（MPEG_4默认） 3（RAW_AMR） 4（AMR_WB） 5（AAC_ADIF） 6（AAC_ADTS） 7（OUTPUT_FORMAT_RTP_AVP） 8（OUTPUT_FORMAT_MPEG2TS） 9（WEBM）
            setVideoEncoder: 2, //编码格式 默认2 h264 0（DEFAULT） 1（H263） 2（H264默认） 3（MPEG_4_SP） 4（VP8） 5（HEVC）
            setAudioEncoder: 3, //音频格式应该是 默认3 aac  0（DEFAULT） 1（AMR_NB） 2（AMR_WB） 3（AAC默认） 4（HE_AAC） 5（AAC_ELD） 6（VORBIS）
          },
          MaxRecordTime: 60, //最大录制时间 单位秒 默认10
          MinRecordTime: 5, //最短录制时间  单位s
          MinTimeText: "时间不能小于5秒，不能大于60秒", //最短时间提示词
          setFeatures: 1001, //设置拍照和录像   1001只拍照   1002只录像   1003两者都可以  默认1003
          setTip: "", //设置按钮上的提示词   长按拍摄等 默认空
          setBackIcon: "", //自定义返回图标 默认向下键头  支持widget  fs 等路径图片
          setBackShow: 1, //设置返回图标是否显示 1是 0否  默认1
          setCameraIcon: "", //自定义切换摄像头图标  支持widget  fs 等路径图片
          setCameraShow: 1, //右上角切换摄像头是否显示 1是 0否 默认1
          cameraInfo: {
            //摄像头 设置样式
            fit_xy: false, //图片是否拉伸占满宽高  默认false
            margin_l: 0, //距左 默认都是0
            margin_r: 35, //距右
            margin_t: 65, //距上
            margin_b: 0, //距下
          },
          foucsInfo: {
            //点击的对焦框 样式
            color: "#cd0000", //线条颜色 默认16AE16
            width: 4, //线条宽度 默认4
          },
          recordInfo: {
            progress_color: "#cd0000", //进度条颜色 默认16AE16
            outside_color: "#DCDCDC", //外圆背景色 默认DCDCDC
            inside_color: "#FFFFFF", //内圆背景色 默认FFFFFF
          },
          confirmInfo: {
            //确认框参数
            fit_xy: false, //图片是否拉伸占满宽高  默认false
            img: "", //设置自定义图片
          },
          cancelInfo: {
            //取消框参数
            fit_xy: false, //图片是否拉伸占满宽高  默认false
            img: "", //设置自定义图片
          },
        },
        function (ret, err) {
          if (ret.status) {
            if (ret.type == "captureSuccess") {
              that.imageFilter(ret.result);
            }
          }
        }
      );
    },

    //图片压缩
    imageFilter(imgPath) {
      let that = this;
      var imageFilter = api.require("imageFilter");
      var imageCachePath = api.cacheDir; //cache://协议对应的真实目录，字符串类型
      imageFilter.compress(
        {
          img: imgPath,
          quality: 0.5,
          size: "800X600",
          save: {
            album: false,
            imgPath: imageCachePath + "/",
            imgName: "cs.jpg",
          },
        },
        function (ret, err) {
          let imgUrl = imageCachePath + "/cs.jpg";
          that.getFileName("pic", imgUrl);
          //文件删除
          var fs = api.require("fs");
          fs.remove(
            {
              path: imgPath,
            },
            function (ret, err) {
              if (ret.status) {
              } else {
              }
            }
          );
        }
      );
    },
    saveTaskitem() {
      // alert(JSON.stringify(this.taskItemList))
    },
    jump() {
      this.taskItemList[this.index].itemResult = 2;
      this.taskItemList[this.index].remark = "";
      this.next();
    },
    back() {
      this.index -= 1;
      if (
        this.taskItemList[this.index].filePath != null &&
        (this.taskItemList[this.index].filePath.indexOf(".mp4") != -1 ||
          this.taskItemList[this.index].filePath.indexOf(".MP4") != -1)
      ) {
        this.standardType = "参照视频";
      } else {
        this.standardType = "参照图片";
      }
      if (this.taskItemList.length > this.index) {
        for (let i = 0; i < this.taskItemList.length; i++) {
          if (this.index != i) {
            this.taskItemList[i].actived = false;
          }
          this.taskItemList[this.index].actived = true;
        }
      }

      this.backLoading = true;
      //如果点检项存在子项，查询子项信息
      if (this.taskItemList[this.index].executeMeans == 4) {
        this.queryTaskItemSelect(this.taskItemList[this.index].id);
      } else {
        this.seletResult = [];
      }
      this.backLoading = false;
    },
    //初始化查询子项
    async queryTaskItemSelect(data) {
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "请稍等...",
      });
      let that = this;
      try {
        let res = await _httpClient.post(
          _httpClient.getApiPrefix() + "/equip/check/queryTaskItemSelect",
          {
            body: { itemId: data },
          }
        );
        Toast.clear();
        if (res.code === 200) {
          if (res.taskSelects) {
            that.seletResult = res.taskSelects;
            //当检测结果无初值的时候，默认合格
            for (let i = 0; i < that.seletResult.length; i++) {
              if (
                that.seletResult[i].isOk == null ||
                that.seletResult[i].isOk == ""
              ) {
                that.seletResult[i].isOk = "1";
                that.taskItemList[this.index].itemResult = "1";
              }
            }
          } else {
            that.seletResult = [];
          }
        } else {
          Toast.fail(res.msg);
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    //下一项
    async next() {
      //判断是否选择项目结果
      if (this.taskItemList[this.index].itemResult == null) {
        // alert(this.taskItemList[this.index].itemResult)
        Toast("请选择检查结果");
        return;
      }

      if (
        this.taskItemList[this.index].executeMeans == 1 ||
        this.taskItemList[this.index].executeMeans == 2
      ) {
        let item = this.taskItemList[this.index];
        if (
          item.resourceList == [] ||
          item.resourceList === undefined ||
          item.resourceList.length === 0
        ) {
          Toast("请完成拍照或视频");
          return;
        }
      }
      this.nextLoading = true;
      //保存本项
      let res = {};
      try {
        res = await _httpClient.post(
          _httpClient.getApiPrefix() + "/equip/check/saveOrUpdate1",
          {
            body: this.taskItemList[this.index],
          }
        );
      } catch (e) {
        res.code = 500;
        res.msg = e;
      }
      this.nextLoading = false;

      if (res.code !== 200) {
        Toast.clear();
        Toast(res.msg);
        return;
      }

      this.index += 1;
      //issue

      if (
        this.taskItemList[this.index].resourceList == null ||
        this.taskItemList[this.index].resourceList == undefined
      ) {
        this.taskItemList[this.index].resourceList = [];
      }

      if (
        this.taskItemList[this.index].filePath != null &&
        (this.taskItemList[this.index].filePath.indexOf(".mp4") != -1 ||
          this.taskItemList[this.index].filePath.indexOf(".MP4") != -1)
      ) {
        this.standardType = "参照视频";
      } else {
        this.standardType = "参照图片";
      }
      if (this.taskItemList.length > this.index) {
        for (let i = 0; i < this.taskItemList.length; i++) {
          if (this.index != i) {
            this.taskItemList[i].actived = false;
          }
        }
        this.taskItemList[this.index].actived = true;
      }
      let that = this;
      that.taskItemList[this.index].siteKey = that.user.site;
      that.taskItemList[this.index].executer = that.user.userName;
      if (that.seletResult.length > 0) {
        that.taskItemList[this.index].selects = that.seletResult;
      }

      //如果点检项存在子项，查询子项信息
      if (that.taskItemList[that.index].executeMeans == 4) {
        that.queryTaskItemSelect(that.taskItemList[that.index].id);
      } else {
        that.seletResult = [];
      }
    },
    //暂存
    async tempSave() {
      //判断是否选择项目结果
      if (this.taskItemList[this.index].itemResult == null) {
        // alert(this.taskItemList[this.index].itemResult)
        Toast("请选择检查结果");
        return;
      }
      this.tempLoading = true;
      let msg = "";
      let ifErr = false;
      //暂存时将所有项都保存了
      for (let i = 0; i <= this.index; i++) {
        try {
          let res = await _httpClient.post(
            _httpClient.getApiPrefix() + "/equip/check/saveOrUpdate1",
            {
              body: this.taskItemList[i],
            }
          );
          if (res.code !== 200) {
            msg += i + 1 + "、";
            ifErr = true;
          }
        } catch (e) {
          msg += i + 1 + "、";
          ifErr = true;
        }
      }
      this.tempLoading = false;
      Toast.clear();

      if (ifErr) {
        Toast("第" + msg + "项暂存失败，请重试");
      } else {
        Toast("暂存成功");
      }
    },
    imageShow() {
      if (this.taskFileList.length > 0) {
        ImagePreview({
          images: this.taskFileList || [],
          showIndicators: true,
          showIndex: false,
        });
      }
    },
    picShow(picIndex) {
      ImagePreview({
        images: this.taskItemList[this.index].resourceList || [],
        showIndicators: true,
        startPosition: picIndex || 0,
        showIndex: false,
      });
    },
    // 图片预览
    previewPictrue(url) {
      ImagePreview([url]);
    },
    //视频播放
    playVedio(filePath) {
      let that = this;
      if (
        api.deviceName.toLowerCase() == "vivo" ||
        api.deviceName.toLowerCase() == "oppo" ||
        api.deviceName.toLowerCase() == "honor"
      ) {
        var videoPlayer = api.require("videoPlayer");
        videoPlayer.play(
          {
            path: filePath.trim(),
            autoPlay: true,
          },
          function (ret, err) {}
        );
      } else {
        that.$ac.openVideo({
          url: filePath.trim(),
        });
      }
    },
    async doCheck() {
      //判断是否选择项目结果
      if (this.taskItemList[this.index].itemResult == null) {
        // alert(this.taskItemList[this.index].itemResult)
        Toast("请选择检查结果");
        return;
      }
      let that = this;
      let err = "";
      //校验当前任务是否存在项目没有拍照或者录制视频
      for (let j = 0; j < that.taskItemList.length; j++) {
        if (
          that.taskItemList[j].executeMeans == 1 ||
          that.taskItemList[j].executeMeans == 2
        ) {
          if (
            that.taskItemList[j].resourceList.length == 0 &&
            that.taskItemList[j].isPass != "1"
          ) {
            //记录缺失项
            if (j == that.taskItemList.length - 1) {
              err += j + 1;
            } else {
              err += j + 1 + "、";
            }
          }
        }
      }
      if (err != "") {
        alert("当前任务第:" + err + "项，未上传图片或者视频，请检查并上传");
        return;
      }
      //插入工厂key和user
      for (let i = 0; i < that.taskItemList.length; i++) {
        that.taskItemList[i].siteKey = that.user.site;
        that.taskItemList[i].executer = that.user.userName;
      }
      that.btnLoading = true;
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "正在保存...",
      });
      let res = await _httpClient.post(
        _httpClient.getApiPrefix() + "/equip/check/saveOrUpdate",
        {
          body: this.taskItemList[this.index],
        }
      );
      Toast.clear();
      that.btnLoading = false;
      Toast(res.msg);
      if (res.code === 200) {
        api.sendEvent({
          name: "result",
          extra: {
            taskCode: that.taskItemList[0].taskKey,
          },
        });
        that.$ac.closeWin();
      }
    },
    async delObj(picUrl, fname) {
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "请稍等...",
      });
      try {
        let res = await _httpClient.delete(
          _httpClient.getApiPrefix() + "/minio/oss/" + fname
        );
        if (res.code === 200) {
          Toast.clear();
          let flist = this.taskItemList[this.index].resourceList;
          for (var i = 0; i < flist.length; i++) {
            if (flist[i] == picUrl) {
              flist.splice(i, 1);
            }
          }
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    startVideoRecord() {
      if (api.systemType == "ios") {
        let that = this;
        let zySmallVideo = api.require("zySmallVideo");
        zySmallVideo.openNew(
          {
            rect: {
              //模块 附于一个frame之上
              x: 0,
              y: 0,
              w: api.frameWidth,
              h: api.frameHeight,
            },
            fixedOn: api.frameName,
            fixed: true,
            videoInfo: {
              //视频高级设置 不懂请勿修改
              //videoSize_w:720,//视频分辨率 宽 默认720
              //videoSize_h:1280,//视频分辨率 高 默认1280
              setOutputFormat: 2, //录制格式 默认2 mp4  0（DEFAULT） 1（THREE_GPP） 2（MPEG_4默认） 3（RAW_AMR） 4（AMR_WB） 5（AAC_ADIF） 6（AAC_ADTS） 7（OUTPUT_FORMAT_RTP_AVP） 8（OUTPUT_FORMAT_MPEG2TS） 9（WEBM）
              setVideoEncoder: 2, //编码格式 默认2 h264 0（DEFAULT） 1（H263） 2（H264默认） 3（MPEG_4_SP） 4（VP8） 5（HEVC）
              setAudioEncoder: 3, //音频格式应该是 默认3 aac  0（DEFAULT） 1（AMR_NB） 2（AMR_WB） 3（AAC默认） 4（HE_AAC） 5（AAC_ELD） 6（VORBIS）
            },
            MaxRecordTime: 60, //最大录制时间 单位秒 默认10
            MinRecordTime: 5, //最短录制时间  单位s
            MinTimeText: "时间不能小于5秒，不能大于60秒", //最短时间提示词
            setFeatures: 1002, //设置拍照和录像   1001只拍照   1002只录像   1003两者都可以  默认1003
            setTip: "", //设置按钮上的提示词   长按拍摄等 默认空
            setBackIcon: "", //自定义返回图标 默认向下键头  支持widget  fs 等路径图片
            setBackShow: 1, //设置返回图标是否显示 1是 0否  默认1
            setCameraIcon: "", //自定义切换摄像头图标  支持widget  fs 等路径图片
            setCameraShow: 1, //右上角切换摄像头是否显示 1是 0否 默认1
            cameraInfo: {
              //摄像头 设置样式
              fit_xy: false, //图片是否拉伸占满宽高  默认false
              //w:120,// 摄像头宽度 默认 120
              //h:92,// 摄像头高度 默认 92
              margin_l: 0, //距左 默认都是0
              margin_r: 35, //距右
              margin_t: 65, //距上
              margin_b: 0, //距下
            },
            foucsInfo: {
              //点击的对焦框 样式
              color: "#cd0000", //线条颜色 默认16AE16
              width: 4, //线条宽度 默认4
            },
            recordInfo: {
              //录制时的参数
              //button_radius:120,//外圆半径 默认120
              //button_inside_radius:90,//内圆半径 默认90
              progress_color: "#cd0000", //进度条颜色 默认16AE16
              outside_color: "#DCDCDC", //外圆背景色 默认DCDCDC
              inside_color: "#FFFFFF", //内圆背景色 默认FFFFFF
              //strokeWidth:15,//进度条宽度 默认15
              //outside_add_size:48,//长按外圆半径变大的Size 默认48
              //inside_reduce_size:30,//长按内圆缩小的Size 默认30
            },
            confirmInfo: {
              //确认框参数
              fit_xy: false, //图片是否拉伸占满宽高  默认false
              img: "", //设置自定义图片
              //w:220,//宽 默认200
              //h:220,//高 默认200
              //margin_r:170, //确认按距右
            },
            cancelInfo: {
              //取消框参数
              fit_xy: false, //图片是否拉伸占满宽高  默认false
              img: "", //设置自定义图片
              //w:220,//宽 默认200
              //h:220,//高 默认200
              //margin_l:170,//确认按距左
            },
          },
          function (ret, err) {
            if (ret.status) {
              // fileUrl = ret.fileUrl
              // document.getElementById('videoPic').src = ret.result
              if (ret.type == "recordSuccess") {
                that.getFileName("video", ret.url);
              }
            }
          }
        );
      } else {
        let that = this;
        let zySmallVideo = that.$ac.require("zySmallVideo");
        zySmallVideo.open(
          {
            MaxRecordTime: 60,
            MinRecordTime: 6, //最短录制时间  单位s
            MinTimeText: "时间不能小于5秒，不能大于60秒", //最短时间提示词
            videoColor: api.systemType == "ios" ? 0xcd0000 : "#cd0000",
            AVAssetExportPreset: "AVAssetExportPreset1280x720",
            mVideoSizeW: 720,
            mVideoSizeH: 1280,
          },
          function (ret, err) {
            if (ret.result == "success") {
              that.getFileName("video", ret.fileUrl);
            }
          }
        );
      }
    },
    showVideoPlay(videoUrl) {
      let that = this;
      if (!videoUrl) {
        Toast("请先录制视频");
        return;
      }
      that.$ac.openVideo({
        url: videoUrl,
      });
    },
    showVideoPlay1(videoUrl) {
      // alert(videoUrl)
      return;
      let that = this;
      let zySmallVideo = that.$ac.require("zySmallVideo");
      if (!that.fileUrl) {
        Toast("请先录制视频");
        return;
      }
      zySmallVideo.getThumbnail(
        {
          fileUrl: that.fileUrl,
        },
        function (ret, err) {
          alert(JSON.stringify(ret));
          // document.getElementById('videoPic').src = ret.filePic;
        }
      );
    },
    clearVideoCache(videoUrl) {
      let zySmallVideo = this.$ac.require("zySmallVideo");
      if (videoUrl != undefined && videoUrl != "" && videoUrl != null) {
        let videoName = videoUrl.substring(videoUrl.lastIndexOf("/") + 1);
        this.delObj(videoUrl, videoName);
      }
      zySmallVideo.clearCache({}, function (ret, err) {
        Toast.success({
          message: "清理成功",
        });
      });
    },
  },
};
</script>
<style>
html,
body {
  font-family: "Open Sans", sans-serif;
  background-color: White;
}

.mg5 {
  margin-right: 5px;
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.container.dwo {
  display: flex;
  justify-content: center;
  align-items: top;
}

.textScroll {
  display: inline-block;
  position: fixed;
  top: 4.5rem;
  bottom: 5px;
  overflow: scroll;
  right: 0;
  width: 100%;
  z-index: 1;
  box-shadow: 0 10px 50px rgba(0, 0, 0, 0.3);
}

.card_under {
  height: 900px;
  /* width: 96%;
  margin: auto;
  background: #ffffff;
  border-radius: 25px;
  box-shadow: 0 10px 50px rgba(0, 0, 0, 0.3);
}

.card_icon {
  text-align: center;
  /* position: absolute; */
  height: 8rem;
  width: 80%;
  margin: 12% 10%;
  background: rgba(35, 180, 237, 1);
  border-radius: 25px;
  box-shadow: 0 10px 50px rgba(0, 0, 0, 0.3);
}

.text {
  font-size: 18px;
  color: #ff0000;
  margin: 8px auto auto 20px;
  line-height: 1.5rem;
  text-align: justify;
  font-weight: 600;
}

.btn_margin {
  margin: 2px 0 0 2%;
  margin-top: 10px;
}

.textEq {
  font-size: 18px;
  color: #696969;
  margin: 20px auto auto 60px;
  line-height: 1.5rem;
  text-align: justify;
  font-weight: 600;
}

.text_scan {
  font-size: 18px;
  color: #4e4a67;
  margin: auto auto auto 40px;
  line-height: 1.5em;
  text-align: justify;
  white-space: nowrap;
}

.img_test {
  margin-top: 20px;
  font-size: 0;
  padding-left: 20px;
}

.content-img {
  height: 60px;
  width: 60px;
  margin-bottom: 20px;
  margin-right: 20px;
  display: inline-block;
}

.content-img > img {
  height: 60px;
  width: 60px;
}

.content-img .image-remove {
  background-color: white;
  color: #ececec;
  font-size: 10px;
  width: 10px;
  height: 10px;
  text-align: center;

  border-radius: 100%;
  transform: rotate(45deg);
  cursor: pointer;
  opacity: 0.5;
  top: 1px;
  right: 1px;
  display: block;
  position: absolute;
}
</style>
